Option Strict On

Imports Excel = Microsoft.Office.Interop.Excel
'Imports Office = Microsoft.Office.Core
Imports System.Text.RegularExpressions

Public Class Properties

    Private Const defaultSearchSymbol As Char = "%"c
    Private Const defaultSearchPattern As String = defaultSearchSymbol & defaultSearchSymbol

    Public Shared Function FindProperties(ByVal rangeToSearch As Excel.Range, ByVal properties As Object) As IList
        Dim rngFound As Excel.Range
        Dim findList As ArrayList = New ArrayList

        Dim rngFoundFirst As Excel.Range

        rngFound = rangeToSearch.Find( _
            defaultSearchPattern, , _
            Excel.XlFindLookIn.xlFormulas, Excel.XlLookAt.xlPart, _
            Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, False)

        While Not rngFound Is Nothing
            If rngFoundFirst Is Nothing Then
                rngFoundFirst = rngFound
            ElseIf rngFound.Address = rngFoundFirst.Address Then
                Exit While
            End If
            Try
                Dim o As Object = rngFound.PivotField
            Catch ex As Exception
                Dim p As ITemplateProperty = CreateTemplateProperty(rngFound, properties)
                If (Not p Is Nothing) Then
                    findList.Add(p)
                End If
            End Try
            rngFound = rangeToSearch.FindNext(rngFound)
        End While
        Return findList
    End Function

    Private Shared Function CreateTemplateProperty(ByRef location As Excel.Range, ByRef properties As Object) As ITemplateProperty
        Dim table As ITemplateTable
        If (IsProperty(location)) Then
            Dim name As String = location.Value.ToString.TrimStart(defaultSearchSymbol)
            Return New TemplateProperty(location, properties, name)
        End If
        Return Nothing
    End Function

    Private Shared Function IsProperty(ByVal location As Excel.Range) As Boolean
        Dim str As String = location.Value.ToString
        Dim match As match = Regex.Match(location.Value.ToString, "^%%\w+")
        If (match.Success) Then
            Return match.Value = str
        Else
            Return False
        End If
    End Function

End Class
